<template>
  <div class="body">
    <div class="table_content">
      <div class="table_filtrate">
        <div class="tf_item">
          <div class="tag">时间范围</div>
          <el-date-picker
            v-model="tableParams.time_interval"
            class="input"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            size="mini"
          />
        </div>

        <div class="tf_item">
          <div class="tag">机构名称/ID</div>
          <el-input
            v-model="tableParams.organization_id_or_name_like"
            class="input_fuzzy_search input"
            placeholder="机构名称/机构ID"
            clearable
            size="mini"
          />
        </div>

        <div class="tf_item">
          <div class="tag">产品名称/ID</div>
          <el-input
            v-model="tableParams.product_id_or_name_like"
            class="input_fuzzy_search input"
            placeholder="产品名称/产品ID"
            clearable
            size="mini"
          />
        </div>

        <div class="tf_item">
          <div class="tag">渠道名称/ID</div>
          <el-input
            v-model="tableParams.channel_id_or_name_like"
            class="input_fuzzy_search input"
            placeholder="渠道名称/渠道ID"
            clearable
            size="mini"
          />
        </div>

        <div class="tf_item">
          <div class="tag">手机号</div>
          <el-input
            v-model="tableParams.mobile"
            class="input_fuzzy_search input"
            placeholder="手机号"
            size="mini"
            clearable
          />
        </div>

        <div class="tf_item" style="margin-right: 30px">
          <div class="tag">助贷类型 </div>
          <el-select
            v-model="tableParams.loan_type"
            placeholder="助贷类型"
            clearable
            size="mini"
            :filterable="true"
            class="inp"
          >
            <el-option
              v-for="item in loan_type_option"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>

        <div class="tf_item" style="margin-right: 30px">
          <div class="tag">进度类型 </div>
          <el-select
            v-model="tableParams.plan"
            placeholder="进度类型"
            clearable
            size="mini"
            :filterable="true"
            class="inp"
          >
            <el-option
              v-for="item in plan_option"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>

        <div class="tf_item" style="margin-right: 30px">
          <div class="tag">地区 </div>
          <el-cascader
            v-model="region_city"
            size="mini"
            placeholder="请选择地区"
            class="inp"
            :props="{ checkStrictly: true }"
            :options="city_data_option"
            clearable
          />
        </div>

        <div class="tf_item">
          <el-button
            type="primary"
            plain
            size="mini"
            @click="loadTableData"
          >搜索</el-button>
          <el-button
            class="btn_export"
            type="info"
            size="mini"
            @click="exportExcelFun()"
          >导出<i class="el-icon-download el-icon--right" /></el-button>

        </div>
      </div>
      <!--
      <div class="table_operate">
        <div class="tool-self">
          <el-button
            class="btn_export"
            type="info"
            size="mini"
            @click="exportExcelFun()"
          >导出<i class="el-icon-download el-icon--right" /></el-button>
        </div>
      </div> -->

      <div class="table-card">
        <el-table
          id="table_id"
          v-loading="loading.table"
          class="table"
          :data="tableData.data"
          :row-class-name="tableRowClassName"
          :border="true"
          size="mini"
        >
          <el-table-column prop="organization_name" label="机构名称" width="120" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span
                slot="reference"
                class="ellipsis custom-link"
                style="font-size: 12px"
              >{{ scope.row.organization_name }}</span>
            </template>
          </el-table-column>

          <el-table-column label="产品" width="90">
            <template slot-scope="scope">
              {{ scope.row.product.name }}</template>
          </el-table-column>

          <el-table-column label="渠道" width="90" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span
                slot="reference"
                class="ellipsis custom-link"
                style="font-size: 12px"
              >{{ scope.row.channel_name }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="name" label="姓名" width="100">
            <template slot-scope="scope">
              {{ scope.row.clue.name }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="身份证" width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{ scope.row.clue.identity }}
            </template>
          </el-table-column>
          <el-table-column label="用户详情" width="80">
            <template slot-scope="scope">
              <el-link
                class="handle"
                type="warning"
                @click="handleDialogInfo(scope.row)"
              >查看</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="年龄" width="50">
            <template slot-scope="scope">
              {{ scope.row.clue.age }}
            </template>
          </el-table-column>
          <el-table-column prop="car" label="车产" width="50">
            <template slot-scope="scope">
              {{ scope.row.clue.car }}
            </template>
          </el-table-column>
          <el-table-column prop="house" label="房产" width="50">
            <template slot-scope="scope">
              {{ scope.row.clue.house }}
            </template>
          </el-table-column>
          <el-table-column prop="accumulation_fund" label="公积金" width="60">
            <template slot-scope="scope">
              {{ scope.row.clue.accumulation_fund }}
            </template>
          </el-table-column>
          <el-table-column prop="social_security" label="社保" width="50">
            <template slot-scope="scope">
              {{ scope.row.clue.social_security }}
            </template>
          </el-table-column>
          <el-table-column prop="insurance" label="保单" width="50">
            <template slot-scope="scope">
              {{ scope.row.clue.insurance }}
            </template>
          </el-table-column>
          <el-table-column prop="clue.work" label="职业" width="100" />
          <el-table-column prop="credit_status" label="信用状况" width="100">
            <template slot-scope="scope">
              {{  scope.row.clue.credit_status }}
            </template>
          </el-table-column>
          <el-table-column prop="business_owner" label="营业执照" width="80">
            <template slot-scope="scope">
              {{ scope.row.clue.business_owner }}
            </template>
          </el-table-column>
          <el-table-column prop="loan_money" label="需求金额" width="80">
            <template slot-scope="scope">
              {{ scope.row.clue.loan_money }}
            </template>
          </el-table-column>
          <el-table-column prop="sesame_score" label="芝麻分" width="80">
            <template slot-scope="scope">
              {{ scope.row.clue.sesame_score }}</template>
          </el-table-column>
          <el-table-column prop="huabei_quota" label="花呗额度" width="80">
            <template slot-scope="scope">
              {{ scope.row.clue.huabei_quota }}</template>
          </el-table-column>
          <el-table-column prop="baitiao_quota" label="白条额度" width="90">
            <template slot-scope="scope">
              {{ scope.row.clue.baitiao_quota }}</template>
          </el-table-column>
          <el-table-column prop="region" label="城市" width="200" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span
                slot="reference"
                class="ellipsis custom-link"
                style="font-size: 12px"
              >{{
                scope.row.clue.province +
                  " " +
                  (scope.row.clue.city? scope.row.clue.city:'') +
                  " " +
                  (scope.row.clue.district? scope.row.clue.district :'')
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="baitiao_quota" label="助贷类型" width="80">
            <template slot-scope="scope">
              {{ scope.row.product.loan_type }}</template>
          </el-table-column>
          <el-table-column prop="plan" label="联系状态" width="100">
            <template slot-scope="scope">
              {{ getPlanText(scope.row.plan) }}
            </template>
          </el-table-column>

          <el-table-column prop="remark" label="跟进内容" width="100" />

          <el-table-column prop="organization_personnel.nickname" label="分配经理" width="100" />

          <el-table-column label="申请时间" width="140">
            <template slot-scope="scope">
              <div>{{ scope.row.createtime }}</div>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-if="!loading.table"
          :current-page="tableParams.page"
          :page-sizes="$pageSize"
          :page-size="tableParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleTableSizeChange"
          @current-change="handleTableCurrentChange"
        />
      </div>
    </div>

    <ClueDetail ref="clueDetailRef" />
  </div>
</template>

<script>
import { convertRange } from '@/utils/clueUtil'
import { apiProductClueListpage } from '@/api/apiCommon'
import { paramsDeleteNull, hidePart } from '@/utils/common'
import { getTableText } from '@/utils/appUtil'
import { exportExcel } from '@/utils/htmlToExcelUtils'
import {
  getCity,
  trCity,
  initTableData,
  initPickerOptions
} from '@/utils/appUtil'
import { getStorageSync } from '@/utils/storageUtils.js'
import {
  getDateDaysAgo,
  getStartOfDayTimestamp,
  formatTimestamp
} from '@/utils/datetimeUtil'
import ClueDetail from '@/components/business/ClueDetail.vue'

export default {
  name: 'Index',
  components: {
    ClueDetail
  },
  data() {
    return {
      tableParams: {
        page: 1,
        size: 30,
        time_interval: [new Date(), new Date()],
        organization_personnel_uid: '',
        channel_id_or_name_like: '',
        mobile: ''
      },
      tableData: {},
      pagination: {},
      tableInfo: {
        status: false
      },
      currentPage4: 1,
      business_select: [],
      organization_select: [],
      fromViewCofing: {
        input_width: '120px',
        label_width: '120px'
      },
      city_data: [],
      dialog_info: {
        status: false,
        data: null
      },
      pickerOptions: {},
      loading: {
        dialog_create: false,
        table: false
      },

      region_city: [], // 省市区地址
      // 选项数据
      city_data_option: [],
      plan_option: [],
      loan_type_option: []
    }
  },
  created() {
    this.reqApiCity()
    this.pickerOptions = initPickerOptions()
    const commonOptionData = getStorageSync('config_current', false)
    this.city_data_option = commonOptionData.city || []
    this.plan_option = commonOptionData.clue.product_clue_plan_v2 || []
    this.loan_type_option = commonOptionData.organization.loantype || []
    // console.log('缓存选项数据', this.plan_option, this.loan_type_option)
    // getStorageSync('config_current', false)
  },
  methods: {
    // 获取表格里的展示文字
    getTableText,
    // 城市转换
    trCity,
    // 日期转换
    formatTimestamp,
    // 导出表格
    exportExcelFun() {
      exportExcel('线索')
    },
    // 列表请求
    loadTableData(is_initpage = true) {
      const _this = this
      console.log(_this.region_city)
      if (is_initpage) {
        _this.tableParams.page = 1
      }
      _this.loading_start('table')
      _this.tableData = initTableData()
      var tableParamsData = { ..._this.tableParams }

      var start_time = getStartOfDayTimestamp(
        tableParamsData['time_interval'][0]
      )
      var end_time =
        getStartOfDayTimestamp(tableParamsData['time_interval'][1]) + 86400

      delete tableParamsData['time_interval']
      tableParamsData['start_time'] = start_time
      tableParamsData['end_time'] = end_time

      if (!tableParamsData['organization_personnel_uid']) {
        delete tableParamsData['organization_personnel_uid']
      }

      if (!tableParamsData['channel_id_or_name_like']) {
        delete tableParamsData['channel_id_or_name_like']
      }

      if (!tableParamsData['mobile']) {
        delete tableParamsData['mobile']
      }
      // 省市区选择增加
      const province = _this.region_city[0] ? _this.region_city[0] : ''
      const city = _this.region_city[1] ? _this.region_city[1] : ''
      const district = _this.region_city[2] ? _this.region_city[2] : ''

      if (province) {
        tableParamsData.province = province
      }
      if (city) {
        tableParamsData.city = city
      }
      if (district) {
        tableParamsData.district = district
      }

      apiProductClueListpage(tableParamsData)
        .then((response) => {
          const result = response
          var tableData = result.data.datalist
          console.log(tableData, 'tableData') 
          // for (var t = 0; t < tableData.data.length; t++) {
          //   tableData.data[t]["createtime"] = formatTimestamp(
          //     tableData.data[t]["createtime"]
          //   );

          //   tableData["data"][t]["identity"] = hidePart(
          //     tableData["data"][t]["identity"]
          //   );
          //   tableData["data"][t]["mobile"] = hidePart(
          //     tableData["data"][t]["mobile"]
          //   );
          //   tableData["data"][t]["car"] = _this.fuStatusCh(
          //     tableData["data"][t]["car"]
          //   );
          //   tableData["data"][t]["house"] = _this.fuStatusCh(
          //     tableData["data"][t]["house"]
          //   );
          //   tableData["data"][t]["accumulation_fund"] = _this.fuStatusCh(
          //     tableData["data"][t]["accumulation_fund"]
          //   );
          //   tableData["data"][t]["social_security"] = _this.fuStatusCh(
          //     tableData["data"][t]["social_security"]
          //   );
          //   tableData["data"][t]["business_owner"] = _this.fuStatusCh(
          //     tableData["data"][t]["business_owner"]
          //   );
          //   tableData["data"][t]["insurance"] = _this.fuStatusCh(
          //     tableData["data"][t]["insurance"]
          //   );
          //   tableData["data"][t]["sesame_score"] = convertRange(
          //     tableData["data"][t]["sesame_score"]
          //   );
          //   tableData["data"][t]["huabei_quota"] = convertRange(
          //     tableData["data"][t]["huabei_quota"]
          //   );
          //   tableData["data"][t]["baitiao_quota"] = convertRange(
          //     tableData["data"][t]["baitiao_quota"]
          //   );
          //   if (tableData["data"][t]["region"]) {
          //     var region = tableData["data"][t]["region"].split(",");
          //     tableData["data"][t]["region"] = trCity(_this.city_data, region);
          //   }
          // }
          _this.tableData = tableData
          _this.loading_end('table')
        })
        .catch(function(result) {
          _this.loading_end('table')
        })
    },
    // 状态转换
    fuStatusCh(status) {
      if (status == 1) {
        return '有'
      } else {
        return '无'
      }
    },
    getPlanText(str) {
      const commonOptionData = getStorageSync('config_current', false)
      const obj = commonOptionData.clue.product_clue_plan || {}
      return obj[str] || ''
    },
    getCreditStatusText(str) {
      const commonOptionData = getStorageSync('config_current', false)
      const objArr = commonOptionData.clue.credit_status_v2 || []
      const obj = {}
      objArr.forEach((item, index) => {
        obj[item.value] = item.label
      })
      // console.log(obj)

      return obj[str] || ''
    },
    // 获取商务人员
    reqApiAgent() {
      const _this = this
      _this.loading_start('table')
      apiAgentList({
        page: 1,
        size: 99,
        status: 'normal',
        group_id: 3
      }).then((response) => {
        const result = response.data.datalist.data
        _this.business_select = result
        _this.loading_end('table')
      })
    },
    // 获取机构列表
    reqApiOrganization(business_uid) {
      const _this = this
      _this.loading_start('table')
      apiOrganizationSelects({
        page: 1,
        size: 99,
        business_uid: business_uid
      }).then((response) => {
        const result = response.data
        _this.organization_select = result.selects
        _this.loading_end('table')
      })
    },
    // 切换商务人员
    changeSelectBusinessuid(business_uid) {
      this.tableParams.o_id = ''
      this.reqApiOrganization(business_uid)
    },
    // 页面跳转
    handleToGoCreate() {
      this.$router.push({ path: '/product/create', query: { id: 0 }})
    },
    // 表格行状态
    tableRowClassName({ row, rowIndex }) {
      if (row['status'] == 'stop') {
        return 'discard-row'
      }
    },
    // 表格操作
    handleTableEdit(index, row) {
      this.$router.push({ path: '/product/update', query: { id: row.id }})
    },
    // 表格恢复
    handleTableRegain(index, row) {
      var _this = this
      var params = {
        id: row.id,
        status: 'normal'
      }
      _this.loading_start('table')
      apiProductUpdatePart(params).then((response) => {
        _this.loading_end('table')
        _this.loadTableData()
      })
    },
    // 表格删除
    handleTableDelete(index, row) {
      const _this = this
      _this.loading_start('table')
      apiProductDelete({
        id: row.id
      }).then((response) => {
        this.$message({
          message: response.msg,
          type: 'success'
        })
        _this.loading_end('table')
        _this.loadTableData()
      })
    },
    // 打开详情
    handleDialogInfo(data) {
      // var dialog_info = this.dialog_info
      // dialog_info.status = true
      // dialog_info.data = data

      // console.log(dialog_info, 'dialog_info')
      // dialog_info.is_show_mobile = false
      // this.dialog_info = dialog_info
      this.$refs.clueDetailRef.onOpenView(data)
    },
    // 数量改变
    handleTableSizeChange(val) {
      this.tableParams.size = val
      this.loadTableData(false)
    },
    // 页数改变
    handleTableCurrentChange(val) {
      this.tableParams.page = val
      this.loadTableData(false)
      // console.log(`当前页: ${val}`);
    },
    // 部分状态改变
    tableUpdateItem(item) {
      var _this = this
      var params = {
        id: item.id,
        push_status: item.push_status,
        entry_status: item.entry_status
      }
      _this.loading_start('table')
      apiProductUpdatePart(params).then((response) => {
        _this.loading_end('table')
      })
    },
    // 获取城市
    reqApiCity() {
      const _this = this
      _this.loading_start('table')
      getCity().then((response) => {
        _this.city_data = response
        _this.loading_end('table')
        _this.loadTableData()
      })
    },
    // 加载开始...
    loading_start(keys) {
      if (Array.isArray(keys)) {
        keys.forEach((key) => {
          this.loading[key] = true
          setTimeout(() => {
            this.loading[key] = false
          }, 5000)
        })
      } else {
        this.loading[keys] = true
        setTimeout(() => {
          this.loading[keys] = false
        }, 5000)
      }
    },
    // 加载结束...
    loading_end(keys) {
      if (Array.isArray(keys)) {
        keys.forEach((key) => {
          this.$nextTick(() => {
            this.loading[key] = false
          })
        })
      } else {
        this.$nextTick(() => {
          this.loading[keys] = false
        })
      }
    }
  }
}
</script>

<style lang="scss">
.details {
}
</style>
